package com.chen.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chen.common.Constants;
import com.chen.entity.MailLog;
import com.chen.service.MailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;

/**
 * rabbitmq配置
 * @author chenchao
 * @date 2022/7/27 17:35
 */

@Configuration
@SuppressWarnings("all")
public class RabbitMQConfig {

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    private static final Logger log = LoggerFactory.getLogger(RabbitMQConfig.class);


    @Resource
    private MailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate() {
        /**
         * data:消息唯一标识
         * ack: 确认消息
         * cause：失败原因
         */
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
//        消息确认回调
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            String msgId = data.getId();
            if (ack) {
                log.info("{}=====》消息发送成功", msgId);
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 1).eq("msgId", msgId));
            } else {
                log.error("{}=====消息发送失败", msgId);
            }
        });

        /**
         * msg:消息主题
         * repCode:响应码
         * repText:相应描述
         * exchange:交换机
         * routingKey: 路由键
         */
        rabbitTemplate.setReturnCallback((msg,repCode,repText,exchange,routingkey)->{
            log.error("{}=====》消息发送失败",msg.getBody());
        });

        return rabbitTemplate;
    }


    //    声明队列
    @Bean
    public Queue queue() {
        return new Queue(Constants.MMAIL_QUEUE_NAME);
    }

    //    声明交换机
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(Constants.MMAIL_EXCHANGE_NAME);
    }

    //    绑定交换机和队列
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(directExchange()).with(Constants.MMAIL_ROUTING_KEY_NAME);
    }


}
